package mia.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;

import mia.entity.AdvertisementEntity;
import mia.entity.AdvertisementTypeEntity;
import mia.entity.AttachmentEntity;
import mia.entity.CategoryEntity;
import mia.entity.UserEntity;
import mia.util.HibernateManager;

public class AdvertisementEntityDAO {

	@SuppressWarnings("unchecked")
	public static AdvertisementEntity getAdvertisementById(Session session,
			int id) {
		Criteria crit = session.createCriteria(AdvertisementEntity.class);
		crit.add(Restrictions.eq("advertisement_id", id));
		List<AdvertisementEntity> list = crit.list();
		if (list.size() > 0)
			return list.get(0);
		else
			return null;
	}

	public static void changeCategoryForAdvertisement(int adv_id, int cate_id) {
		Session session = HibernateManager.getSession();
		session.beginTransaction();

		CategoryEntity kategoria = CategoryEntityDAO
				.getCategoryById(session, 1);

		Criteria crit = session.createCriteria(AdvertisementEntity.class);
		crit.add(Restrictions.eq("advertisement_id", adv_id));
		List<AdvertisementEntity> list = crit.list();
		if (list.size() > 0) {
			AdvertisementEntity advertisement = list.get(0);
			advertisement.setCategory(kategoria);
			session.save(advertisement);
		}
		session.getTransaction().commit();
		session.close();
	}

	@SuppressWarnings("unchecked")
	public static List<AdvertisementEntity> get10LastAdvertisements(int count) {

		Session session = HibernateManager.getSession();
		Criteria crit = session.createCriteria(AdvertisementEntity.class);
		crit.addOrder(Order.asc("startDate"));
		crit.setMaxResults(count);
		List<AdvertisementEntity> list = crit.list();
		session.close();
		return list;
	}

	@SuppressWarnings("unchecked")
	public static List<AdvertisementEntity> getUserAdvertisements(
			UserEntity user) {
		Session session = HibernateManager.getSession();
		Criteria crit = session.createCriteria(AdvertisementEntity.class);
		crit.add(Restrictions.eq("user", user));
		List<AdvertisementEntity> list = crit.list();
		session.close();
		return list;
	}

	@SuppressWarnings("unchecked")
	public static List<AdvertisementEntity> getAdvertisements(String titleLike,
			String contentLike, Date addedAfter, Date activeToDate,
			CategoryEntity category, AdvertisementTypeEntity type) {
		Session session = HibernateManager.getSession();
		Criteria crit = session.createCriteria(AdvertisementEntity.class);
		if (titleLike != null && titleLike != "") {
			crit.add(Restrictions.like("title", "%" + titleLike + "%"));
		}
		if (contentLike != null && contentLike != "") {
			crit.add(Restrictions.like("content", "%" + contentLike + "%"));
		}

		if (category != null)
			crit.add(Restrictions.eq("category", category));

		if (type != null)
			crit.add(Restrictions.eq("type", type));

		// DATE
		List<AdvertisementEntity> list = crit.list();
		List<AdvertisementEntity> result = new ArrayList<AdvertisementEntity>();
		if (addedAfter != null && activeToDate != null) {
			for (AdvertisementEntity adv : list) {
				Date addDate = adv.getStartDate();
				Date endDate = adv.getExpireDate();
				System.out.println(addDate);
				System.out.println(endDate);
				if (addDate != null && endDate != null) {
					if (addDate.after(addedAfter)
							&& endDate.before(activeToDate))
						result.add(adv);
				}
			}
		} else
			result = list;
		session.close();
		return result;
	}

	public static int maxValueOfAttachment() {
		Session sess = null;
		try {
			SessionFactory fact = new Configuration().configure()
					.buildSessionFactory();
			sess = fact.openSession();
			String SQL_QUERY = "select max(attachment_id) from mia.entity.AttachmentEntity";
			Query query = sess.createQuery(SQL_QUERY);
			List<Integer> list = query.list();
			System.out.println("Max value: " + list.get(0));
			sess.close();
			return list.get(0);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			FacesMessage msg = new FacesMessage("Error " + e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
			return 0;
		}
	}

	public static int maxValueOfAdvertisement() {
		Session sess = null;
		try {
			SessionFactory fact = new Configuration().configure()
					.buildSessionFactory();
			sess = fact.openSession();
			String SQL_QUERY = "select max(advertisement_id) from mia.entity.AdvertisementEntity";
			Query query = sess.createQuery(SQL_QUERY);
			List<Integer> list = query.list();
			System.out.println("Max value: " + list.get(0));
			sess.close();
			return list.get(0);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			FacesMessage msg = new FacesMessage("Error " + e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
			return 0;
		}
	}

	public static boolean moreThanThree(int id) {

		Session session = HibernateManager.getSession();
		Criteria crit = session.createCriteria(AttachmentEntity.class);
		crit.add(Restrictions.eq("advertisement", id));
		@SuppressWarnings("unchecked")
		List<CategoryEntity> lista = crit.list();
		if (lista.size() >= 3) {

			return false;
		} else {
			return true;
		}
	}
}
